
#ifndef __SERIALPORT_H__
#define __SERIALPORT_H__

#define WM_COMM_BREAK_DETECTED		WM_USER+1
#define WM_COMM_CTS_DETECTED			WM_USER+2
#define WM_COMM_DSR_DETECTED			WM_USER+3
#define WM_COMM_ERR_DETECTED			WM_USER+4
#define WM_COMM_RING_DETECTED			WM_USER+5
#define WM_COMM_RLSD_DETECTED			WM_USER+6
#define WM_COMM_RXCHAR						WM_USER+7
#define WM_COMM_RXFLAG_DETECTED		WM_USER+8
#define WM_COMM_TXEMPTY_DETECTED	WM_USER+9 

class CSerialPort
{														 
public:
	int m_nWriteSize; 
	void ClosePort();
	CSerialPort();
	virtual		~CSerialPort();
											
	BOOL		InitPort(CWnd* pPortOwner, UINT portnr = 1, UINT baud = 19200, char parity = 'N', UINT databits = 8, UINT stopbits = 1, DWORD dwCommEvents = EV_RXCHAR, UINT writebuffersize = 1024);
	HANDLE	m_hComm;

	BOOL		StartMonitoring();
	BOOL		RestartMonitoring();
	BOOL		StopMonitoring();

	DWORD		GetWriteBufferSize();
	DWORD		GetCommEvents();
	DCB			GetDCB();

	void		WriteToPort(char* string);
	void		WriteToPort(char* string,int n);
	void		WriteToPort(unsigned char* string,int n);
	void		WriteToPort(LPCTSTR string);
	void		WriteToPort(LPCTSTR string,int n);

protected:
	void		ProcessErrorMessage(char* ErrorText);
	static	UINT	CommThread(LPVOID pParam);
	static	void	ReceiveChar(CSerialPort* port, COMSTAT comstat);
	static	void	WriteChar(CSerialPort* port);

	CWinThread*			m_Thread;

	CRITICAL_SECTION	m_csCommunicationSync;
	BOOL				m_bThreadAlive;

	HANDLE				m_hWriteEvent;
	HANDLE				m_hShutdownEvent;

	HANDLE				m_hEventArray[3];

	OVERLAPPED			m_ov;
	COMMTIMEOUTS		m_CommTimeouts;
	DCB					m_dcb;

	CWnd*				m_pOwner;

	UINT				m_nPortNr;
	char*				m_szWriteBuffer;
	DWORD				m_dwCommEvents;
	DWORD				m_nWriteBufferSize;
};

#endif __SERIALPORT_H__


